/** 注意要使用reducer 数组不能为空，或则至少要有一个初始值*/
//TypeError: Reduce of empty array with no initial value
/*[].reduce((p,c,i,a)=>{

}) //*/


//求总价
/*const total = [{price: 10, count: 1}, {price: 20, count: 2}, {price: 30, count: 3}]
  .reduce((prev, current, index, arr) => {
    return prev + current.price * current.count;
  }, 0 /!*第一次的prev*!/);
console.log(total); //140*/

//求平均数
/*const avg = [1, 2, 3, 4, 5, 6].reduce((prev, current, index, arr) => {
  if (index === arr.length - 1) {
    return (prev+current)/arr.length
  }
  return prev + current;
}, 0);
console.log(avg); //3.5*/


//reduce实现
Array.prototype.reduce = function (callback, prev) {
  for (let i = 0; i < this.length; ++i) {
    if(typeof prev === 'undefined'){
      prev = callback(this[i], this[i + 1], i + 1, this);
      i++;
    }else{
      prev = callback(prev, this[i], i, this);
    }
  }
  return prev;
};
